<?php
namespace Ext;
class MallexRequest extends \Phalcon\Http\Request
{
    public function getQuery($name = null, $filters = null, $defaultValue = null)
    {
        $ret = null;
        $val = array_key_exists($name, $_GET) ? $_GET[$name] : null;
        if (is_array($val)) return $val;
        if ($val !== null) {
            if (true === is_array($filters)) {
                foreach ($filters as $filter) {
                    $name = $this->filter($val, $filter);
                }
                $ret = $val;
            } else {
                $ret = $this->filter($val, $filters);
            }
        } else {
            $ret = $defaultValue;
        }
        return $ret;
    }

    public function getPost($name = null, $filters = null, $defaultValue = null)
    {
        $ret = null;
        if (null === $name) {
            return $_POST;
        }
        $val = array_key_exists($name, $_POST) ? $_POST[$name] : null;
        if (is_array($val)) return $val;
        if ($val !== null) {
            if (true === is_array($filters)) {
                foreach ($filters as $filter) {
                    $name = $this->filter($val, $filter);
                }
                $ret = $val;
            } else {
                $ret = $this->filter($val, $filters);
            }
        }
        return $ret;
    }

    //文件上传base64格式
    public function saveBase64Images($imagesData, $extensions = array('jpg', 'png', 'jpeg'), $savePath = 'images', $reName = true)
    {
        global $config;
        if ($reName === true) $fileName = '';
        if (substr($savePath, -1) != '/') $savePath = $savePath . '/';
        $dir = $savePath;
        //\Ext\Utils::mkdir($config->application->upfileDir . $dir, 755);
        $dir = $dir . date('Y-m-d') . '/';
        $path = $config->application->upfilePath . $dir;
        $dir = $config->application->upfileDir . $dir;
        \Ext\Utils::mkdir($dir);
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imagesData, $result)) {
            if (empty($result[2])) return false;
            if (!in_array($result[2], $extensions)) return false;
            if ($reName === true || $reName === false) $fileName = time() . '_' . rand(1000, 9999) . '.' . $result[2];
            else $fileName = $reName . '.' . $result[2];
            $save = file_put_contents($dir . $fileName, base64_decode(str_replace($result[1], '', $imagesData)));
            if (!$save) {
                return false;
            }
            $ext = pathinfo($fileName, PATHINFO_EXTENSION);
            $file = $dir . $fileName;
            //$fileExtensions = \Ext\File::getExtension($file);
            //压缩图片
            if (in_array($ext, array('jpg', 'png', 'jpeg', 'gif'))) {
                $im = new \Ext\ImagickService();
                $im->open($file);
                $im->resize(750);
                $im->autoOrientationImage();
                $im->save_to($file);
            }
            return $path . $fileName;
        }
        return false;
    }

    //文件上传  form 或者 base64格式   stream文件流
    public function getUpload($key, array $extensions, $savePath = 'images', $reName = true, $uploadType = 'form')
    {
        global $config;
        $new_files = array();
        if (substr($savePath, -1) != '/') $savePath = $savePath . '/';
        $dir = $savePath;
        if ($reName === true) $dir = $dir . date('Y-m-d') . '/';
        if($reName!==true && $reName!==false)
        {
            if(substr($reName,-1)!='.')$reName .='.';
        }
        $path = $config->application->upfilePath . $dir;
        $dir = $config->application->upfileDir . $dir;
        if (!\Ext\Utils::mkdir($dir)) return false;
        if ($uploadType == 'form') {
            if ($this->hasFiles()) {
                foreach ($this->getUploadedFiles() as $k => $file) {
                    if ($key != $file->getKey()) continue;
                    if (!in_array(strtolower($file->getExtension()), $extensions)) return false;
                    if ($reName === true) $fileName = time() . '_' . rand(1000, 9999) . '.' . $file->getExtension();
                    elseif ($reName === false) $fileName = $file->getName();
                    else $fileName = $reName . $file->getExtension();
                    $fileName = iconv("UTF-8", "gb2312", $fileName);
                    if (!$file->moveTo($dir . $fileName)) return false;
                    $fileName = iconv("gb2312", "UTF-8", $fileName);
                    $new_files[] = $path . $fileName;
                }
                if (count($new_files) == 1) $new_files = $new_files[0];
                else {
                    //@todo 循环验证文件扩展名是否正确
                    return $new_files;
                }
                //$new_files;
            } else return false;
        } elseif ($uploadType == 'base64') {
            $base64_image_content = $this->get($key);
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
                if (empty($result[2])) return false;
                if (!in_array($result[2], $extensions)) return false;
                if ($reName === true || $reName === false) $fileName = time() . '_' . rand(1000, 9999) . '.' . $result[2];
                else $fileName = $reName . '.' . $result[2];
                $save = file_put_contents($dir . $fileName, base64_decode(str_replace($result[1], '', $base64_image_content)));
                if (!$save) {
                    return false;
                }
            } else return false;
        } elseif ($uploadType == 'stream') {
            $ext = pathinfo($key, PATHINFO_EXTENSION);
            if (!in_array($ext, $extensions)) return false;
            if ($reName === true) $fileName = time() . '_' . rand(1000, 9999) . '.' . $ext;
            else $fileName = $key;
            $save = file_put_contents($dir . $fileName, file_get_contents("php://input"));
            if (!$save) {
                return false;
            }
        } else return false;
        $new_files = $path . $fileName;
        //严格验证检查文件扩展名
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);
        $file = $dir . $fileName;
        //exif_read_data();$exif['Orientation']
        /*$fileExtensions = \Ext\File::getExtension($file);
        if (!is_array($fileExtensions)) {
            @unlink($file);
            return false;
        }
        if (!in_array($ext, $fileExtensions)) {
            @unlink($file);
            return false;
        }*/
        //压缩图片
        if (in_array($ext, array('jpg', 'png', 'jpeg', 'gif'))) {
            $im = new \Ext\ImagickService();
            $im->open($file);
            $im->autoOrientationImage();
            $im->resize(750);
            $im->save_to($file);
        }
        return $new_files;
    }


    public function filter($value, $filter = null)
    {
        $ret = null;
        switch ($filter) {
            case 'int':
                $ret = intval(trim($value));
                break;
            case 'floatval':
                $ret = floatval(trim($value));
                break;
            case 'string':
                $ret = $this->sql_replace(htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8'));
                break;
            case 'striptags':
                $ret = $this->sql_replace(htmlspecialchars(strip_tags(trim($value)), ENT_QUOTES, 'UTF-8'));
                break;
            case 'mobile':
                if (preg_match("/^1[3|4|5|6|7|8|9]{1}[0-9]{9}$/", $value)) {
                    $ret = $value;
                }
                break;
            case 'email':
                if (preg_match("/([a-z0-9]*[-_\.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?/i", $value)) {
                    $ret = $value;
                }
                break;
            case 'date':
                if (strtotime(date('Y-m-d H:i:s', strtotime($value))) === strtotime($value)) {
                    $ret = $value;
                }
                break;
            case 'json':
                $ret = json_decode($value, true);
                break;
            default:
                $ret = $this->sql_replace(trim($value));
                break;
        }
        return $ret;
    }

    /* 移动端判断 */
    public function isMobile()
    {
        $md = new \Ext\MobileDetect();
        return $md->isMobile();
    }

    //防止sql注入
    private function sql_replace($keyword)
    {
        $keyword = str_replace("'", '', $keyword);
        $keyword = str_replace('"', '', $keyword);
        //$keyword = str_replace("]",'',$keyword);
        //$keyword = str_replace("[",'',$keyword);
        $keyword = str_replace("\\", '', $keyword);
        //$keyword = mysql_real_escape_string($keyword);
        return $keyword;
    }
}